# -*- coding: utf-8 -*-

import sys
sys.path.append('/home/crawler/src')
import commonlib
import download
import traceback
import time
import datetime
import cherrypy
import re
import os
from Cheetah.Template import Template
from threading import Thread

DOWNLOAD_PATH = '/home/hoangnamhai/HarvestedData/nhaccuatui/english/'
PREFIX = '/uploads/nhaccuatui/english/'
ROOT = 'http://lopngoaingu.com/english-GT/Grammar/'

class Webservice():
    
    @cherrypy.expose
    def index(self, url=''):
        try:
            if url != '': url = commonlib.urlJoin(ROOT, url)
            fname = ''
            if url.endswith('mp3'):
                fsize, fname = download.downloadNCT(url, DOWNLOAD_PATH, PREFIX)
            elif re.search(r'(png|gif|jpeg|jpg|bmp|ico)$', url):
                fname = commonlib.downloadImage(url, DOWNLOAD_PATH, PREFIX)
            sfolder = ''
            if fname != '':
                ext = commonlib.extractWithRegEx(r'\.(\w+)$', fname, 1)
                sfolder = "files/{0}.{1}".format(commonlib.getMd5FileName(url), ext)
            t = Template(file='form.template.html', searchList=[{'result': fname, 'filepath': sfolder}])
            return str(t)
        except:
            return str(sys.exc_info())
        
    @cherrypy.expose
    def hash(self, url=''):
        try:
            hashUrl = ''
            if url != '':
                hashUrl = commonlib.getMD5Hash(url)
            t = Template(file='hash.template.html', searchList=[{'result': hashUrl}])
            return str(t)
        except:
            return str(sys.exc_info())
    
def startWebservice():
    cherrypy.config.update({'server.socket_port':88, 
        'server.socket_host':'0.0.0.0', 
        'engine.autoreload.on': True, 
        'tools.sessions.on': True,
        'tools.encode.encoding': 'utf-8',
        'server.environment': 'development'})
    conf = {'/files': {'tools.staticdir.dir': DOWNLOAD_PATH,
                        'tools.staticdir.on': True,
                        'tools.staticdir.content_types': {'png': 'image/png', 'mp3': 'audio/mp3'}}}
    cherrypy.quickstart(Webservice(), '/', config=conf)
    
if __name__ == '__main__':
    
    Thread(target=startWebservice).start()
    